//
//  WeaponsTableViewController.swift
//  Weapons
//
//  Created by YQ05 on 2018/4/2.
//  Copyright © 2018年 YQ05. All rights reserved.
//

import UIKit

class WeaponsTableViewController: UITableViewController {
//    var weapons = ["AUG","AWM","DP28"]
//    var weaponTypes = ["自动步枪","狙击枪","冷兵器"]
//    var origins = ["奥地利","英国","中国"]
//    var weaponImages = ["aug","awm","dp28"]
    
//var favourites = Array(repeating: false, count: 11)
    
//    @IBAction func favBtnTap(_ sender: UIButton) {
//        let btnPos = sender.convert(CGPoint.zero, to: self.tableView)
//
//        print("爱心按钮所在位置\(btnPos)")
//        let indexPath = tableView.indexPathForRow(at:btnPos)!
//
//        print("爱心按钮所在行\(indexPath)")
//
//        self.favourites[indexPath.row] = !self.favourites[indexPath.row]
//
//        let cell = tableView.cellForRow(at: indexPath) as! CardCell
//
//        cell.favorite = self.favourites[indexPath.row]
//    }
    
 
    
    
    
    var weapons : [Weapon] = []
 

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor(named:"theme")!
        ]
     
        loadJson()
    }
    
    func loadJson() {
        let coder = JSONDecoder()
        
        do{
            let url = Bundle.main.url(forResource: "weapons", withExtension: "json")!
            
            let data = try Data(contentsOf:url)
            weapons = try coder.decode([Weapon].self, from: data)
        } catch {
            print(error)
        }
    }
    
//    func saveToJson(){
//        let coder = JSONEncoder()
//
//        do {
//         let data =  try coder.encode(weapons)
//            let saveUrl = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("weapons.json")
//            try data.write(to: saveUrl)
//            print("保存成功！路径：",saveUrl)
//
//        } catch {
//            print("编码错误：",error)
//        }
//    }

    @IBAction func favBtnTap(_ sender: UIButton) {
        let btnPos = sender.convert(CGPoint.zero, to: self.tableView)
        //把自己的坐标转换成父容器的坐标
        
                print("爱心按钮所在位置\(btnPos)")
                let indexPath = tableView.indexPathForRow(at:btnPos)!
        
                print("爱心按钮所在行\(indexPath)")
        
                self.weapons[indexPath.row].favorite = !self.weapons[indexPath.row].favorite
        
                let cell = tableView.cellForRow(at: indexPath) as! CardCell
        
                cell.favorite = self.weapons[indexPath.row].favorite
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        
    }

    // MARK: - Table view data source  自定义与系统提供删除互相排斥
//    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
//        weapons.remove(at: indexPath.row)
//        weaponTypes.remove(at: indexPath.row)
//        origins.remove(at: indexPath.row)
//        weaponImages.remove(at: indexPath.row)
//        favourites.remove(at: indexPath.row)
//
//        print(weapons.count)
//        tableView.deleteRows(at: [indexPath], with: .automatic)
//    }
    
    //左侧
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let favAction = UIContextualAction(style: .normal, title: "Like") { (_, _, completion) in
            
          
            
             completion(true)
        }
        favAction.image = #imageLiteral(resourceName: "fav")
        favAction.backgroundColor = UIColor.purple
        
        let config = UISwipeActionsConfiguration(actions: [favAction])
        return config
    }
 
    //右侧
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delAction = UIContextualAction(style: .destructive, title: "删除") { (_, _, completion) in
            self.weapons.remove(at: indexPath.row)
            
//            self.weaponTypes.remove(at: indexPath.row)
//            self.origins.remove(at: indexPath.row)
//            self.weaponImages.remove(at: indexPath.row)
            //self.weapons.remove(at: indexPath.row)
            
            print(self.weapons.count)
            tableView.deleteRows(at: [indexPath], with: .automatic)
            
             completion(true)
        }
        let shareAction = UIContextualAction(style: .normal, title: "share") { (_, _, completion) in
            let text = " 这是绝地求生中的武器\(self.weapons[indexPath.row].name)!"
            let image = UIImage(named: self.weapons[indexPath.row].image)!
            
            let ac = UIActivityViewController(activityItems: [text,image], applicationActivities: nil)
            
            if let pc = ac.popoverPresentationController{
                if let cell = tableView.cellForRow(at: indexPath){
                    pc.sourceView = cell
                    pc.sourceRect = cell.bounds
                }
            }
            self.present(ac,animated: true)
            
            completion(true)
            
        }
        shareAction.backgroundColor = UIColor.orange
        
        let config = UISwipeActionsConfiguration(actions: [delAction,shareAction])
        return config
        
        
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return weapons.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let id = String(describing:CardCell.self)
        let cell = tableView.dequeueReusableCell(withIdentifier: id, for: indexPath) as! CardCell
        
        let weapon = weapons[indexPath.row]
        
        cell.typeLabel.text = weapon.type
        cell.weapon.text = weapon.name
        cell.originLabel.text = weapons[indexPath.row].origin
        cell.backImageView.image = UIImage(named: weapons[indexPath.row].image)
        cell.favorite = weapons[indexPath.row].favorite

        // Configure the cell...

        return cell
    }
 

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if segue.identifier == "showweaponDetail"{
            let row = tableView.indexPathForSelectedRow!.row
            
            let destination = segue.destination as! DetailController
            
            destination.weapon = weapons[row]
        }
        

        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
       
    }
    
    
    @IBAction func backToHome(segue:UIStoryboardSegue){
        
    }

}
